package com.itcast.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.itcast.domain.PageBean;
import com.itcast.domain.Product;
import com.itcast.service.ProductService;

public class ProductServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 请求/响应中文乱码
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		try {
			// 获取请求数据
			int pageNo = Integer.parseInt(request.getParameter("pageNo"));
			int pageSize = Integer.parseInt(request.getParameter("pageSize"));

			// 获取数据库数据
			ProductService products = new ProductService();
			List<Product> list = products.findAll(pageNo, pageSize);
			int totalCount = products.findTotalCount();
			int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);

			// 封装数据
			PageBean<Product> pageBean = new PageBean<Product>();
			pageBean.setPageNo(pageNo);
			pageBean.setPageSize(pageSize);
			pageBean.setTotalCount(totalCount);
			pageBean.setTotalPage(totalPage);
			pageBean.setContent(list);

			String jsonObj = JSONObject.toJSONString(pageBean);
			response.getWriter().write(jsonObj);

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
